package imse.team1.inventory.ws;

import imse.team1.errs.InternalErrorElement;
import imse.team1.inventory.dal.CatalogQueryService;
import imse.team1.orders.data.*;

import java.io.IOException;
import java.util.*;

/**
 * @author Eugen, 6/18/12 7:38 PM
 */
public class CatalogServiceSkeleton implements CatalogServiceSkeletonInterface {

    private static List<String> transporationEndpoints = new ArrayList<String>();

    static {
        Properties props = new Properties();
        try {
            props.load(CatalogServiceSkeleton.class.getResourceAsStream("/transportation-agents.properties"));
            for (String value : props.stringPropertyNames()){
                transporationEndpoints.add(props.getProperty(value));
            }
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            throw new RuntimeException(e);
        }
    }

    private CatalogQueryService catalogQueryService = new CatalogQueryService();

    public Order computeTotalPrice(Order order) {
        List<String> names = new ArrayList<String>();

        for (PackageUnit pu : order.getPackageUnit()){
            for (OrderItem item : pu.getOrderItem()){
                if (names.contains(item.getName()) == false){
                    names.add(item.getName());
                }
            }
        }

        try {
            List<String> prices = catalogQueryService.checkValidNames(names);
            Map<String, Double> itemPrices = new HashMap<String, Double>();
            for (int i = 0; i < names.size(); i++){
                itemPrices.put(names.get(i), Double.parseDouble(prices.get(i + 1)));
            }
            double totalItemPrice = 0;
            for (PackageUnit pu : order.getPackageUnit()){
                for (OrderItem item : pu.getOrderItem()){
                    Double itemPrice = itemPrices.get(item.getName());
                    totalItemPrice += (itemPrice.doubleValue()*item.getQty());
                }
            }
            order.setTotalCosts(order.getTransportationCosts()+totalItemPrice);
        } catch (Exception e) {
            // shame on me
        }
        return order;
    }

    public imse.team1.orders.data.OrderStatus checkOrder(OrderItem[] items) throws InternalFaultMessage {
        OrderStatus status = new OrderStatus();
        List<String> names = new ArrayList<String>();
        for (OrderItem item : items) {
            names.add(item.getName());
        }
        try {
            List<String> result = catalogQueryService.checkValidNames(names);
            OrderStatusChoice_type0 payload = new OrderStatusChoice_type0();
            String[] badItemReason = new String[result.size() - 1];
            if (result.get(0) != null) {// there are missing items
                status.setStatus(StatusEnum.INVALID);
                for (int i = 1; i < result.size(); i++) {
                    badItemReason[i - 1] = result.get(i);
                }
                payload.setBadItemReason(badItemReason);
                status.setOrderStatusChoice_type0(payload);
            } else {
                status.setStatus(StatusEnum.OK);
                payload.setOrderid("X");// to be filled in later
                status.setOrderStatusChoice_type0(payload);
            }
        } catch (Exception e) {
            InternalFaultMessage ex = new InternalFaultMessage();
            InternalErrorElement reason = new InternalErrorElement();
            reason.setReason("Catalog Service is down. Try again later.");
            ex.setFaultMessage(reason);
            throw ex;
        }
        return status;
    }

    public String[] getTransporationEndpoints() {
        return transporationEndpoints.toArray(new String[0]);
    }
}
